package utils;

import org.apache.commons.io.IOUtils;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

/**
 * Created by Gipxy group
 * Date: 3/13/12
 */
public class ImageUtil {
    public static byte[] toByte(String imgFileName) {
        return toByte(ImageUtil.class.getResourceAsStream("../data/image/" + imgFileName));
    }

    public static byte[] toByte(String imgFileName, String base) {
        return toByte(ImageUtil.class.getResourceAsStream(base + imgFileName));
    }
    
    public static byte[] toByte(InputStream is) {
        try {
            return IOUtils.toByteArray(is);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
    }

    public static byte[] getOneLargeImage() {
        return toByte(ImageUtil.class.getResourceAsStream("../data/image/compressed_air_main.jpg"));
    }

    public static byte[] getOneRelatedImage() {


        return toByte(ImageUtil.class.getResourceAsStream("../data/image/sl_low_flow_air_knives_100x100.png"));
    }
    public static byte[] resize(byte[] origBytes,int w, int h){
    	if (origBytes == null)
    		return null;
    	
    	try {
    		return gaeResize(origBytes, w, h);
    	} catch (Exception e) {
    		e.printStackTrace();
    		return origBytes;
    	}
    	
    }
    
    //GAE service, very good quality
    public static byte[] gaeResize(byte[] oldImageData,  int dWidth, int dHeight) {
         ImagesService imagesService = ImagesServiceFactory.getImagesService();

         Image oldImage = ImagesServiceFactory.makeImage(oldImageData);
         
         //no need 
         if (oldImage.getWidth() * oldImage.getHeight() < 1.2 * dWidth * dHeight )
        	 return oldImageData;
         
         Transform resize = ImagesServiceFactory.makeResize(dWidth, dHeight);

         Image newImage = imagesService.applyTransform(resize, oldImage);

         byte[] newImageData = newImage.getImageData();

         return newImageData;
    }
}
